# Copyright (c) 2020 Red Hat, Inc. All rights reserved. This copyrighted
# material is made available to anyone wishing to use, modify, copy, or
# redistribute it subject to the terms and conditions of the GNU General Public
# License v.2 or later.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""The "case" command."""
import re

from kpet import cmd_misc
from kpet import data
from kpet import misc


def build(cmds_parser, common_parser):
    """Build the argument parser for the case command."""
    _, action_subparser = cmd_misc.build(
        cmds_parser,
        common_parser,
        "case",
        help='Case',
    )
    list_parser = action_subparser.add_parser(
        "tree",
        help='Output the (filtered) tree of cases.',
        parents=[common_parser],
    )
    list_parser.add_argument('regexes', metavar='REGEX', nargs='*',
                             default=[],
                             help='Regular expression fully matching '
                                  'slash-separated paths of cases to output. '
                                  'Matching cases are output with their '
                                  'sub-cases.')


def main(args):
    """Execute the `case` command."""
    if not data.Base.is_dir_valid(args.db):
        misc.raise_invalid_database(args.db)
    database = data.Base(args.db)
    if args.action == 'tree':
        def print_case(prefix, subprefix, case, regexes):
            suffix = (" " + repr(case.name)) if case.name is not None else ""
            if regexes:
                if any(r.fullmatch(case.path) for r in regexes):
                    print(prefix + case.path + suffix)
                    regexes = []
            else:
                print(prefix + case.id + suffix)
            if regexes:
                subcase_prefix = prefix
                subcase_subprefix = subprefix
            subcases = list((case.cases or {}).values())
            for i, subcase in enumerate(subcases):
                if not regexes:
                    if i + 1 < len(subcases):
                        subcase_prefix = subprefix + "|-- "
                        subcase_subprefix = subprefix + "|   "
                    else:
                        subcase_prefix = subprefix + "`-- "
                        subcase_subprefix = subprefix + "    "
                print_case(subcase_prefix, subcase_subprefix,
                           subcase, regexes)

        print_case("", "", database.case,
                   [re.compile(r) for r in args.regexes] or
                   [re.compile(".*")])
    else:
        misc.raise_action_not_found(args.action, args.command)
